import javax.swing.text.DefaultStyledDocument;
import java.awt.font.GlyphJustificationInfo;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by L.jp
 * Description:
 * User: 86189
 * Date: 2022-11-12
 * Time: 20:46
 */
class ListNode {
      int val;
      ListNode next;
      ListNode(int x) { val = x; }
}
public class Solution {
    /*public int[] reversePrint(ListNode head) {
        //栈
        Stack<Integer> stack=new Stack<>();
        ListNode cur=head;
        int len=0;
        while(cur!=null){
            stack.push(cur.val);
            cur=cur.next;
            len++;
        }
        int[] ret=new int[len];
        int i=0;
        while(!stack.isEmpty()){
            ret[i++]=stack.pop();
        }
        return ret;
    }*/
    
    //递归
    /*ArrayList<Integer> list=new ArrayList<>();
    public void dfs(ListNode head){
        if(head==null){
            return;
        }
        dfs(head.next);
        list.add(head.val);
    }
    public int[] reversePrint(ListNode head){
        dfs(head);
        int[] ret=new int[list.size()];
        for(int i=0;i<ret.length;i++){
            ret[i]=list.get(i);
        }
        return ret;
    }*/
    
    //法三：先得到链表也就是数组的长度，然后再遍历链表把值倒序插入数组
    public int[] reversePrint(ListNode head){
        ListNode cur=head;
        int len=0;
        //计算链表长度
        while (cur!=null){
            cur=cur.next;
            len++;
        }
        int[] ret=new int[len];
        cur=head;
        //再次遍历链表，把链表的节点倒序插入数组
        while (cur!=null){
            ret[len-1]=cur.val;
            --len;
            cur=cur.next;
        }
        return ret;
    }
}
